package com.winter.service;

import com.google.common.base.Strings;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.winter.mapper.DictEntryMapper;
import com.winter.mapper.FinBondMapper;
import com.winter.mapper.FinContentLikeInfoMapper;
import com.winter.mapper.FinCpaperMapper;
import com.winter.mapper.FinDepositReceiptMapper;
import com.winter.mapper.FinFavInfoMapper;
import com.winter.mapper.FinManageMapper;
import com.winter.mapper.FinOnlineMapper;
import com.winter.mapper.FinUnderlineMapper;
import com.winter.mapper.IcompanyCardMapper;
import com.winter.mapper.UserInfoMapper;
import com.winter.model.DictEntry;
import com.winter.model.FinBond;
import com.winter.model.FinContentLikeInfo;
import com.winter.model.FinCpaper;
import com.winter.model.FinDepositReceipt;
import com.winter.model.FinManage;
import com.winter.model.FinOnline;
import com.winter.model.FinUnderline;
import com.winter.model.IcompanyCard;
import com.winter.model.QuotationPlatform;
import com.winter.model.UserInfo;
import com.winter.util.Constants;
import com.winter.util.Result;
import com.winter.util.ResultCode;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

@Service
public class FinCpaperService {

    @Autowired
    private FinCpaperMapper finCpaperMapper;

    @Autowired
    private DictEntryMapper dictEntryMapper;

    @Autowired
    private FinFavInfoMapper finFavInfoMapper;

    @Autowired
    private FinBondMapper finBondMapper;

    @Autowired
    private FinUnderlineMapper finUnderlineMapper;

    @Autowired
    private FinManageMapper finManageMapper;

    @Autowired
    private FinDepositReceiptMapper finDepositReceiptMapper;

    @Autowired
    private FinOnlineMapper finOnlineMapper;

    @Autowired
    private FinOnlineService finOnlineService;

    @Autowired
    private FinBondService finBondService;

    @Autowired
    private FinUnderlineService finUnderlineService;

    @Autowired
    private FinManageService finManageService;

    @Autowired
    private FinDepositReceiptService finDepositReceiptService;

    /**
     * 点赞
     */
    @Autowired
    private FinContentLikeInfoMapper finContentLikeInfoMapper;

    @Autowired
    private UserInfoMapper userInfoMapper;

    @Autowired
    private IcompanyCardMapper icompanyCardMapper;

    /**
     * 查询报价平台票据列表
     *
     * @return List
     */
    public Result queryPageList(Integer pageNumber, Integer pageSize, String direct, String trade_mode, String fund_type, String accept, String userNo, String sortName, String sort, String key) {
        if (pageNumber == null) {
            pageNumber = Constants.PAGENUMBER;
        }
        if (pageSize == null) {
            pageSize = Constants.PAGESIZE;
        }
        PageHelper.startPage(pageNumber, pageSize, false);
        List<FinCpaper> finCpaperList = finCpaperMapper.queryPageList(direct, trade_mode, fund_type, accept, sortName, sort, key);

        if (finCpaperList.size() > 0) {
            for (FinCpaper finCpaper : finCpaperList) {
                String photoPath = null;
                String photoType = finCpaper.getPhotoType();
                if (!Strings.isNullOrEmpty(photoType)) {
                    if (photoType.equals("0")) {
                        // 获取创建人头像
                        String createUser = finCpaper.getCreateUser();
                        UserInfo userInfo = userInfoMapper.selectByUserNo(createUser);
                        if (userInfo != null) {
                            String custImgUrl = userInfo.getCustImgUrl();
                            if (!Strings.isNullOrEmpty(custImgUrl)) {
                                finCpaper.setAvatar(userInfo.getCustImgUrl());
                            }
                        } else {
                            //(数据类型)(最小值+Math.random()*(最大值-最小值+1))
                            //(int)(1+Math.random()*(10-1+1))
                            int verycode = (int) (1 + Math.random() * (70 - 1 + 1));
                            photoPath = "/p2p/images/imgthumbs/headimg_" + verycode + ".jpg";
                            finCpaper.setAvatar(photoPath);
                        }
                    } else {
                        //(数据类型)(最小值+Math.random()*(最大值-最小值+1))
                        //(int)(1+Math.random()*(10-1+1))
                        int verycode = (int) (1 + Math.random() * (70 - 1 + 1));
                        photoPath = "/p2p/images/imgthumbs/headimg_" + verycode + ".jpg";
                        finCpaper.setAvatar(photoPath);
                    }
                }
                finCpaper.setFinFavStatus("0");
                finCpaper.setIsLike("0");
                if (!Strings.isNullOrEmpty(userNo)) {
                    // 点赞
                    List<FinContentLikeInfo> isLike = finContentLikeInfoMapper.getIsLike(finCpaper.getId(), "1", "4", userNo);
                    if (isLike.size() > 0) {
                        finCpaper.setIsLike("1");
                    }
                    // 收藏
                    Long aLong = finFavInfoMapper.get(finCpaper.getId(), "1", 4, userNo);
                    if (aLong > 0) {
                        finCpaper.setFinFavStatus("1");
                    }
                }
                getTypeName(finCpaper);
            }
        }

        PageInfo<FinCpaper> pageInfo = new PageInfo<>(finCpaperList);
        return Result.success(pageInfo);
    }

    public void getTypeName(FinCpaper finCpaper) {
        String tradeMode = "";
        String fundType = "";
        String accept_ = "";
        String ticketType = "";
        // 方向
        DictEntry dictEntry = get("DC_BILL_DIRECTION", finCpaper.getDirect());
        if (dictEntry != null) {
            finCpaper.setDirect(dictEntry.getDictname());
        }
        // 模式
        if (!Strings.isNullOrEmpty(finCpaper.getTradeMode())) {
            String[] split = finCpaper.getTradeMode()
                                      .split(",");
            for (String s : split) {
                DictEntry dictEntry1 = get("DC_BILL_MODEL", s);
                if (dictEntry1 != null) {
                    tradeMode += dictEntry1.getDictname() + ",";
                }

            }
            finCpaper.setTradeMode(tradeMode.substring(0, tradeMode.length() - 1));
        }
        //形式
        if (!Strings.isNullOrEmpty(finCpaper.getFundType())) {
            String[] split = finCpaper.getFundType()
                                      .split(",");
            for (String s : split) {

                DictEntry dictEntry1 = get("DC_BILL_FORM", s);
                if (dictEntry1 != null) {
                    fundType += dictEntry1.getDictname() + ",";
                }
            }
            finCpaper.setFundType(fundType.substring(0, fundType.length() - 1));
        }
        //承兑行
        if (!Strings.isNullOrEmpty(finCpaper.getAccept())) {
            String[] split = finCpaper.getAccept()
                                      .split(",");
            for (String s : split) {
                DictEntry dictEntry1 = get("DC_BILL_ACCEPTBANK", s);
                if (dictEntry1 != null) {
                    accept_ += dictEntry1.getDictname() + ",";
                }
            }
            finCpaper.setAccept(accept_.substring(0, accept_.length() - 1));
        }

        //承兑行
        if (!Strings.isNullOrEmpty(finCpaper.getTicketType())) {
            String[] split = finCpaper.getTicketType()
                                      .split(",");
            for (String s : split) {
                DictEntry dictEntry1 = get("DC_BILL_TYPE", s);
                if (dictEntry1 != null) {
                    ticketType += dictEntry1.getDictname() + ",";
                }
            }
            finCpaper.setTicketType(ticketType.substring(0, ticketType.length() - 1));
        }
    }

    public DictEntry get(String type, String chiType) {
        DictEntry dictEntry = dictEntryMapper.get(type, chiType);
        return dictEntry;
    }

    /**
     * 通过id查询报价平台票据信息
     */
    public Result getFinCpaperBean(Long id, String userNo) {
        FinCpaper i = finCpaperMapper.selectByPrimaryKey(id);
        // 获取type类型名称
        getTypeName(i);
        // 默认没有收藏
        i.setFinFavStatus("0");
        i.setIsLike("0");
        if (!Strings.isNullOrEmpty(userNo)) {
            Long count = finFavInfoMapper.get(id, "1", 4, userNo);
            if (count > 0) {
                i.setFinFavStatus("1");
            }
            // 点赞
            List<FinContentLikeInfo> isLike = finContentLikeInfoMapper.getIsLike(i.getId(), "1", "4", userNo);
            if (isLike.size() > 0) {
                i.setIsLike("1");
            }
        }
        return Result.success(i);
    }

    /**
     * 新增报价平台票据
     */
    public Result insertCpaperBean(FinCpaper finCpaper) {
        if (Strings.isNullOrEmpty(finCpaper.getCreateUser())) {
            return Result.failure(ResultCode.USER_NOT_LOGGED_IN);
        }
        if (Strings.isNullOrEmpty(finCpaper.getDirect())) {
            return Result.failure(ResultCode.PARAM_IS_BLANK, "请选择方向");
        }
        if (Strings.isNullOrEmpty(finCpaper.getTradeMode())) {
            return Result.failure(ResultCode.PARAM_IS_BLANK, "请选择模型");
        }
        if (Strings.isNullOrEmpty(finCpaper.getTicketType())) {
            return Result.failure(ResultCode.PARAM_IS_BLANK, "请选择票种");
        }
        if (Strings.isNullOrEmpty(finCpaper.getFundType())) {
            return Result.failure(ResultCode.PARAM_IS_BLANK, "请选择形式");
        }
        if (Strings.isNullOrEmpty(finCpaper.getTerm())) {
            return Result.failure(ResultCode.PARAM_IS_BLANK, "请选择剩余期限");
        }
        if (Strings.isNullOrEmpty(finCpaper.getAccept())) {
            return Result.failure(ResultCode.PARAM_IS_BLANK, "请选择承兑行");
        }
        if (Strings.isNullOrEmpty(finCpaper.getRateBeg()) && Strings.isNullOrEmpty(finCpaper.getRateEnd())) {
            return Result.failure(ResultCode.PARAM_IS_BLANK, "请输入利率");
        }
        if (Strings.isNullOrEmpty(finCpaper.getMonEnd()) && Strings.isNullOrEmpty(finCpaper.getMonBeg())) {
            return Result.failure(ResultCode.PARAM_IS_BLANK, "请输入金额");
        }
        if (Strings.isNullOrEmpty(finCpaper.getContact())) {
            return Result.failure(ResultCode.PARAM_IS_BLANK, "请输入联系方式");
        }


        UserInfo userInfo = userInfoMapper.selectByUserNo(finCpaper.getCreateUser());
        String orgNo = userInfo.getOrgNo();
        IcompanyCard icompanyCard = icompanyCardMapper.selectByPrimaryKey(Long.valueOf(orgNo));
        // 公司信息
        finCpaper.setUserName(userInfo.getUserName());
        finCpaper.setUserCom(icompanyCard.getCompanyName());
        finCpaper.setUserDepart(userInfo.getDepart());
        finCpaper.setUserPost(userInfo.getPost());
        finCpaper.setUserEmail(userInfo.getOrgEmail());
        finCpaper.setUserQq(userInfo.getQq() + "");
        finCpaper.setUserWx(userInfo.getWxNo());
        finCpaper.setTopTime(new Date());
        finCpaper.setInfoSrc("0");
        // 组装数据
        finCpaper.setPhotoType("0");
        finCpaper.setStas("3");
        finCpaper.setCreatetime(new Date());
        finCpaper.setUpdatetime(new Date());
        finCpaper.setUpdateUser(finCpaper.getCreateUser());
        finCpaper.setIsvalid("1");
        finCpaper.setAuditing("0");
        finCpaper.setRateUnit("1");
        finCpaper.setCommentCount(new BigDecimal("0"));
        finCpaper.setFavCount(new BigDecimal("0"));
        finCpaper.setLikeCount(new BigDecimal("0"));
        finCpaper.setCommentFlag("1");
        finCpaper.setLikeFlag("1");
        finCpaper.setReplayFlag("1");
        finCpaperMapper.insertSelective(finCpaper);
        return Result.success();
    }

    public Result updateCpaper(FinCpaper finCpaper) {
        if (Strings.isNullOrEmpty(finCpaper.getCreateUser())) {
            return Result.failure(ResultCode.USER_NOT_LOGGED_IN);
        }
        if (finCpaper.getId() == null) {
            return Result.failure(ResultCode.PARAM_IS_BLANK, "主键id不能为空");
        }
        if (Strings.isNullOrEmpty(finCpaper.getDirect())) {
            return Result.failure(ResultCode.PARAM_IS_BLANK, "请选择方向");
        }
        if (Strings.isNullOrEmpty(finCpaper.getTradeMode())) {
            return Result.failure(ResultCode.PARAM_IS_BLANK, "请选择模型");
        }
        if (Strings.isNullOrEmpty(finCpaper.getTicketType())) {
            return Result.failure(ResultCode.PARAM_IS_BLANK, "请选择票种");
        }
        if (Strings.isNullOrEmpty(finCpaper.getFundType())) {
            return Result.failure(ResultCode.PARAM_IS_BLANK, "请选择形式");
        }
        if (Strings.isNullOrEmpty(finCpaper.getTerm())) {
            return Result.failure(ResultCode.PARAM_IS_BLANK, "请选择剩余期限");
        }
        if (Strings.isNullOrEmpty(finCpaper.getAccept())) {
            return Result.failure(ResultCode.PARAM_IS_BLANK, "请选择承兑行");
        }
        if (Strings.isNullOrEmpty(finCpaper.getRateBeg()) || Strings.isNullOrEmpty(finCpaper.getRateEnd())) {
            return Result.failure(ResultCode.PARAM_IS_BLANK, "请输入利率");
        }
        if (Strings.isNullOrEmpty(finCpaper.getMonEnd())) {
            return Result.failure(ResultCode.PARAM_IS_BLANK, "请输入金额");
        }
        if (Strings.isNullOrEmpty(finCpaper.getContact())) {
            return Result.failure(ResultCode.PARAM_IS_BLANK, "请输入联系方式");
        }
        finCpaper.setUpdatetime(new Date());
        finCpaperMapper.updateByPrimaryKeySelective(finCpaper);
        return Result.success("修改成功");
    }

    /**
     * 首页 (报价平台列表)
     */
    public Result quoteList(String userNo) {
        if (Strings.isNullOrEmpty(userNo)) {
            userNo = "userNo";
        }
        QuotationPlatform platform = new QuotationPlatform();

        FinOnline finOnline = finOnlineMapper.selectByIdKey();
        if (finOnline != null) {
            Result onlineBean = finOnlineService.queryFinId(finOnline.getId(), userNo);
            if (onlineBean.getData() != null) {
                FinOnline online = (FinOnline) onlineBean.getData();
                online.setQuotaType("线上");
                platform.setFinOnline(online);
            }
        }

        FinUnderline finUnderline = finUnderlineMapper.selectByIdKey();
        if (finUnderline != null) {
            Result underlineBean = finUnderlineService.getFinUnderlineId(finUnderline.getId(), userNo);
            if (underlineBean.getData() != null) {
                FinUnderline underline = (FinUnderline) underlineBean.getData();
                underline.setQuotaType("线下");
                platform.setFinUnderline(underline);
            }
        }

        FinDepositReceipt finDepositReceipt = finDepositReceiptMapper.selectByIdKey();
        if (finDepositReceipt != null) {
            Result receiptBean = finDepositReceiptService.details(finDepositReceipt.getId(), userNo);
            if (receiptBean.getData() != null) {
                FinDepositReceipt receipt = (FinDepositReceipt) receiptBean.getData();
                receipt.setQuotaType("存单");
                platform.setFinDepositReceipt(receipt);
            }
        }

        FinManage finManage = finManageMapper.selectByIdKey();
        if (finManage != null) {
            Result manageBean = finManageService.getFinManageId(finManage.getId(), userNo);
            if (manageBean.getData() != null) {
                FinManage manage = (FinManage) manageBean.getData();
                manage.setQuotaType("理财");
                platform.setFinManage(manage);
            }
        }

        FinCpaper finCpaper = finCpaperMapper.selectByIdKey();
        if (finCpaper != null) {
            Result cpaperBean = getFinCpaperBean(finCpaper.getId(), userNo);
            if (cpaperBean.getData() != null) {
                FinCpaper cpaper = (FinCpaper) cpaperBean.getData();
                cpaper.setQuotaType("票据");
                platform.setFinCpaper(cpaper);
            }
        }

        FinBond finBond = finBondMapper.selectByIdKey();
        if (finBond != null) {
            Result bondBean = finBondService.getFinBondId(finBond.getId(), userNo);
            if (bondBean.getData() != null) {
                FinBond bond = (FinBond) bondBean.getData();
                bond.setQuotaType("债券");
                platform.setFinBond(bond);
            }
        }

        return Result.success(platform);
    }
}
